package com.weishaoying.thrift.learn.service.asyn;

import com.meituan.service.mobile.mtthrift.callback.OctoObserver;
import com.meituan.service.mobile.mtthrift.callback.OctoThriftCallback;
import com.weishaoying.thrift.learn.entity.User;
import com.weishaoying.thrift.learn.service.UserService;
import org.apache.thrift.TException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.List;

/**
 * IDL方式异步 - 2.Callback
 *
 * @author WeiShaoying
 * @date 2018/9/12
 */
public class CallbackMain {

    public static void main(String[] args) throws InterruptedException, IOException {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("client.xml");
        UserService.AsyncIface client = (UserService.AsyncIface) beanFactory.getBean("clientProxy");
        Thread.sleep(5000);

        OctoThriftCallback<UserService.AsyncClient.getUserById_call, User> getUserByIdCallback = new OctoThriftCallback();
        getUserByIdCallback.addObserver(new OctoObserver<User>() {

            @Override
            public void onSuccess(User user) {
                System.out.println("----getUserByIdCallback.onSuccess(): result = " + user);
                System.out.println("\n");
            }

            @Override
            public void onFailure(Throwable e) {
                System.out.println("----getUserByIdCallback.onFailure()");
                e.printStackTrace();
            }
        });

        OctoThriftCallback<UserService.AsyncClient.getAllUsers_call, List<User>> getAllUsersCallback = new OctoThriftCallback();
        getAllUsersCallback.addObserver(new OctoObserver<List<User>>() {
            @Override
            public void onSuccess(List<User> users) {
                System.out.println("----getAllUsersCallback.onSuccess()\n");
                users.forEach(System.out::println);
                System.out.println("\n");
            }

            @Override
            public void onFailure(Throwable e) {
                System.out.println("----getAllUsersCallback.onFailure()");
                e.printStackTrace();
            }
        });

        try {
            System.out.println("----------开始调用： client.getUserById()----------");
            client.getUserById(123, getUserByIdCallback);
            client.getAllUsers(getAllUsersCallback);
            System.out.println("----------client.getAllUsers() 结束 ----------\n");

        } catch (TException e) {
            e.printStackTrace();
        }

        System.in.read(); //防止主线程退出
    }
}
